package com.alumni_circle.core.security;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alumni_circle.core.config.RedisCache;
import com.alumni_circle.core.utils.JwtUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 龙小虬
 * @since 2020-08-01 14:00
 *
 * 用户退出登录成功返回类
 */
@Component
public class SuccessLogoutHandler implements LogoutSuccessHandler {

    @Resource
    JwtUtils jwtUtils;

    @Resource
    RedisCache redisCache;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //清理token数据
        String token = httpServletRequest.getHeader("Access-Token");
        String key = jwtUtils.validateToken(token).get("key").toString();
        if(redisCache.hasKey(key)) {
            redisCache.deleteObject(key);
        }
        //返回成功退出的json数据
        Map<String,String> map = new HashMap<>();
        map.put("退出成功","200");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter printWriter = httpServletResponse.getWriter();
        //清理token
        redisCache.deleteObject(key);
        System.out.println(map.toString());
        JSON json = JSONUtil.parse(map);
        printWriter.write(json.toString());
    }
}
